# -*- coding: utf-8 -*- # 
import   os  
os.putenv("http_proxy",   "http://10.7.8.180:8080")   
os.putenv("https_proxy",   "http://10.7.8.180:8080")   
import wx
import types
import data
from data import passUTF8
from data import BookListGrid
import douban.service
from booklistTbl import BookListPanel
from data import get as getAppAttr
from booksearch import bookSearchFrame
class mainFrame(wx.Frame):
    def __init__(self,parent = None, id = -1,
                    title = "Book Master Main"):
        size = (1024,768)
        wx.Frame.__init__(self,parent,id,title,size=size)
        self.initView()
    
    def initView(self):
        
        self.statusBar = self.CreateStatusBar()
        
        self.basicSP = wx.SplitterWindow(self)

        #self.listPanel = wx.Panel(self.basicSP,style=wx.SUNKEN_BORDER)
        self.listPanel = wx.Panel(self.basicSP)
        self.shelfSP = wx.SplitterWindow(self.listPanel)
        self.setBookShelf()
        
        self.bookshelf.Hide()
        self.outShelf.Hide()
        self.shelfSP.Initialize(self.bookshelf)
        self.shelfSP.SplitHorizontally(self.bookshelf, self.outShelf, 0)
        
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.shelfSP, 1, wx.EXPAND)
        self.listPanel.SetSizer(box)
        
        
        #self.bookExpandPanel = wx.Panel(self.basicSP,style=wx.SUNKEN_BORDER)
        self.bookExpandPanel = wx.Panel(self.basicSP)
        self.bookExpandSP = wx.SplitterWindow(self.bookExpandPanel)
        self.initBookTable()

        self.initBookDetail()
        
        self.booktablepanel.Hide()
        self.bookExpandSP.Initialize(self.booktablepanel)
        self.bookExpandSP.SplitHorizontally(self.booktablepanel, self.bookDetail, 0)
        
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.bookExpandSP, 1, wx.EXPAND)
        #box.Add(self.bookDetail, 1, wx.EXPAND)
        self.bookExpandPanel.SetSizer(box)

        self.listPanel.Hide()
        self.bookExpandPanel.Hide()
        self.basicSP.Initialize(self.listPanel)
        self.basicSP.SplitVertically(self.listPanel, self.bookExpandPanel, 0)
        self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGING,
                  self.OnSashChanging, self.basicSP)
        self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED,
                  self.OnSashChanged, self.basicSP)
        self.Bind(wx.EVT_BUTTON, self.OnBookSearch,self.searchbookBtn)
    
    def initBookTable(self):
        #self.booktable= wx.ListCtrl(self)
        self.booktablepanel = wx.Panel(self.bookExpandSP)
        
        self.searchPanel = wx.Panel(self.booktablepanel)
        self.searchbookTextFld =searchTextFld= wx.TextCtrl(self.searchPanel)
        self.searchbookBtn = searchbookBtn = wx.Button(self.searchPanel,label=getAppAttr("bottonsStr")["00001"])
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(searchTextFld, 1, wx.EXPAND)
        box.Add(searchbookBtn, 0, wx.EXPAND)
        self.searchPanel.SetSizer(box)

        #self.booktable= BookListGrid(self.booktablepanel)
        self.booktable=BookListPanel(self.booktablepanel)
        #self.booktable= wx.ListCtrl(self.booktablepanel)
        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.searchPanel, 0, wx.EXPAND)
        box.Add(self.booktable, 1, wx.EXPAND)
        self.booktablepanel.SetSizer(box)
        
        
    def setBookTable(self):
        booktbl = self.booktable
        

    def initBookDetail(self):
        self.bookDetail= wx.TextCtrl(self.bookExpandSP)

    def setBookShelf(self):
        self.bookshelf = wx.TreeCtrl(self.shelfSP)
        slfRoot = self.bookshelf.AddRoot(data.getRootName())
        self.AddTreeNodes(slfRoot,data.getBookSelfs(),self.bookshelf)
        self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.bookshelf)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.bookshelf)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.bookshelf)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.bookshelf)
        #self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.onShelfRightClk, self.bookshelf)
        self.Bind(wx.EVT_TREE_ITEM_MENU, self.onShelfRightClk, self.bookshelf)

        # Expand the first level
        self.bookshelf.Expand(slfRoot)
        
        self.shelfMenu = wx.Menu()
        menuList = data.getShelfPopMenu()
        for item in menuList:
            subMenu = self.shelfMenu.Append(-1,item[0])
            self.listPanel.Bind(wx.EVT_MENU,getattr(self,item[1]),subMenu)
        
        self.outShelf = wx.TreeCtrl(self.shelfSP)
        slfRoot = self.outShelf.AddRoot(data.getRootName())
        self.AddTreeNodes(slfRoot,data.getBookSelfs(),self.outShelf)
        self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.outShelf)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.outShelf)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.outShelf)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.outShelf)
        #self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.onShelfRightClk, self.bookshelf)
        self.Bind(wx.EVT_TREE_ITEM_MENU, self.onShelfRightClk, self.outShelf)

    def AddTreeNodes(self, parentItem, items,shelf):
        """
        Recursively traverses the data structure, adding tree nodes to
        match it.
        """
        for item in items:
            if type(item) == str or type(item) == types.UnicodeType:
                #print item
                shelf.AppendItem(parentItem, item)
            else:
                newItem = shelf.AppendItem(parentItem, item[0])
                self.AddTreeNodes(newItem, item[1],shelf)
                
    def GetItemText(self, evt):
        item = evt.GetItem()
        shelf = self.getShelf(evt.GetId())
        if item:
            return shelf.GetItemText(item)
        else:
            return ""
        
    def getShelf(self,id):
        return self.FindWindowById(id)
    def OnItemExpanded(self, evt):
        #print "OnItemExpanded: ", self.GetItemText(evt.GetItem())
        self.statusBar.SetStatusText("%s%s" % ("OnItemExpanded: ",self.GetItemText( evt)))

    def OnItemCollapsed(self, evt):
        #print "OnItemCollapsed:", self.GetItemText(evt.GetItem())
        self.statusBar.SetStatusText("%s%s" % ("OnItemCollapsed: ",self.GetItemText(evt)))

    def OnSelChanged(self, evt):
        #print "OnSelChanged:   ", self.GetItemText(evt.GetItem())
        self.statusBar.SetStatusText("%s%s" % ("OnSelChanged: ",self.GetItemText(evt)))
        

    def OnActivated(self, evt):
        #print "OnActivated:    ", self.GetItemText(evt.GetItem())
        self.statusBar.SetStatusText("%s%s" % ("OnActivated: ",self.GetItemText(evt)))
    def onShelfRightClk(self,evt):
        pos = evt.GetPoint()
        #pos = self.bookshelf.ScreenToClient(pos)
        self.selectItem = evt.GetItem()
        self.selectShelf = self.getShelf(evt.GetId())
        self.selectShelf.PopupMenu(self.shelfMenu,pos)
        
        pass
    def onAddSubShelf(self,evt):
        print "onAddSubShelf"
        dlgStrList = data.getAddSubShelfDlg()
        dlg = wx.TextEntryDialog(self,dlgStrList[0],dlgStrList[1],dlgStrList[2])
        if(dlg.ShowModal() == wx.ID_OK):
            print "OK"
            subName = dlg.GetValue();
            parentItem = self.selectItem
            if self.chkShelfHave(subName,parentItem) == False:
                data.showErrMsgDig("00001")
            else:
                self.selectShelf.AppendItem(parentItem, subName)
        
    def onDelShelf(self,evt):
        print "onDelShelf"
        parentItem = self.selectItem
        self.selectShelf.Delete(parentItem)
        
    def onDelAllSub(self,evt):
        print "onDelAllSub"
        parentItem = self.selectItem
        self.selectShelf.DeleteChildren(parentItem)
        pass
        
    def onChgShelfName(self,evt):
        print "onChgShelfName"
        dlgStrList = data.getAddSubShelfDlg()
        item = self.selectItem
        dlg = wx.TextEntryDialog(self,dlgStrList[0],dlgStrList[1],self.selectShelf.GetItemText(item))
        if(dlg.ShowModal() == wx.ID_OK):
            print "OK"
            parentItem = self.selectShelf.GetItemParent(item)
            subName = dlg.GetValue();
            if self.chkShelfHave(subName,parentItem) == False:
                data.showErrMsgDig("00001")
            else:
                self.selectShelf.SetItemText(item, subName)
    def chkShelfHave(self,shelfName,shelf):
        item, cookie = self.selectShelf.GetFirstChild(shelf)
        while item:
            if self.selectShelf.GetItemText(item) == shelfName :
                return False
            item, cookie = self.selectShelf.GetNextChild(shelf,cookie)

    def OnSashChanging(self, evt):
        print "OnSashChanging:", evt.GetSashPosition()
    
    def OnSashChanged(self, evt):
        print "OnSashChanged:", evt.GetSashPosition()
    def OnSearch(self,evt):
        # Please use your own api key instead. e.g. :
        #APIKEY = "99fb85ac4722a091cdf29104d567e1b3"
        #APIKEY = None
        APIKEY = "23eeeb4347bdd26bfc6b7ee9a3b755dd"
        client = douban.service.DoubanService(api_key=APIKEY)
        isbn = "八月"
        #feed = client.SearchMovie("Monty Python")
        feed = client.SearchBook(isbn)
        for movie in feed.entry:
            print "%s: %s" % (movie.title.text, movie.GetAlternateLink().href)
    def OnBookSearch(self, evt):
        self.bookSearchFrame = bookSearchFrame(self)
        self.bookSearchFrame.ShowModal()
        if self.bookSearchFrame.select is not None:
            print self.bookSearchFrame.select